<?php

/**
 * 应用程序的公共控制器基础类
 *
 * 可以在这个类中添加方法来完成应用程序控制器共享的功能。
 */
abstract class Controller_Abstract extends QController_Abstract
{
/**
	 * 2011-9-18
	 */
	protected $curr_page=1;	
	protected $page_size=10; 
	//排序列
	protected $orderkey='id';
	//排序方式
	protected $ordertype='asc';
	
	//分页参数
	protected $pagination = null;
	
	//搜索参数
	protected $param=null;
	
	/**
	 * 
	 *2011-12-23-下午11:58:03 by 460932465
	 * @access 通用删除...
	 * @param 条件数组 $array
	 * @param 删除模式
	 */
	function delete($array,$mode = NULL)
	{
		QDB::getConn()->startTrans();
		try {
		$this->union_table->deleteWhere($array);
		QDB::getConn()->completeTrans(true);	
		} catch (Exception $e) {
		QDB::getConn()->completeTrans(FALSE);
		return $this->error($e->getmessage());	
		}
		return $this->success('删除成功');
	}
	/**
	 * 
	 *2011-12-22-下午05:16:37 by 460932465
	 * @access 通用搜索...
	 */
 	function lists($append_data = NULL)
	{
		//获取搜索参数
		$this->get_param();
		//初始化分页信息
		$this->_format_page_info();
		
		//关联表
		//$this->union_table = $union_table;
		if (!is_null($append_data))$this->param = array_merge($this->param,$append_data);
		
		$dis_param = new helper_disposeparam($this->param);
		$sql = $dis_param->getsql();//OUT PUT用
		$_SESSION['lastsql'] = $sql;//OUT PUT用
		$obj = call_user_func_array(array($this->union_table,'find'), $sql);
		$item = $obj->limitPage($this->curr_page,$this->page_size)
					->order(' '.$this->orderkey.' '.$this->ordertype)
					->fetchPagination($this->pagination)
					->getall();
		$this->_view['item'] = $item;
		$this->_view['pagination'] = $this->pagination;	
		$this->_view['orderField'] = $this->orderkey;
		$this->_view['orderDirection'] = $this->ordertype;
		
	}
	
	function output($append_data = NULL,$fileds = '*')
	{
		//获取搜索参数
		$this->get_param();
		//初始化分页信息
		$this->_format_page_info();
		//关联表
		//$this->union_table = $union_table;
		if (!is_null($append_data))$this->param = array_merge($this->param,$append_data);
		$dis_param = new helper_disposeparam($this->param);
		$obj = call_user_func_array(array($this->union_table,'find'), $dis_param->getsql());
		
		$item = $obj->setColumns($fileds)->asArray()->getall();
		
		$output = new Helper_dboutput($item);
		$output->output_txt();
	}
	
	
	//------------
	/**
	 * 
	 *2011-12-20-下午02:13:02 by 460932465
	 * @access 初始化分页信息...
	 */
	protected function _format_page_info()
	{
		//当前页码
		$this->curr_page= isset($this->_context->pageNum)?intval($this->_context->pageNum):1;
		$this->orderkey=isset($this->_context->orderField)?trim($this->_context->orderField):'id';
		$this->ordertype=isset($this->_context->orderDirection)?$this->_context->orderDirection:'desc';
		$this->page_size=isset($this->_context->numPerPage)?intval($this->_context->numPerPage):$this->page_size;
		
		
		//dump($this->param);
	}
	/**
	 * 
	 * 成功返回DWZ 格式...
	 * @param 提示信息 $message
	 */
	protected function success($message)
	{
		$this->_dwzjson(200, $message);
	}
	/**
	 * 
	 * 失败返回DWZ 格式...
	 * @param 提示信息 $message
	 */
	protected function error($message)
	{
		$this->_dwzjson(300, $message);
	}
	/**
	 * 
	 *2011-12-17-下午08:26:40 by 460932465
	 * @return 登陆超时
	 * @param unknown_type $message
	 */
	protected function nologin($message)
	{
		$this->_dwzjson(301, $message);
	}
	/**
	 * 
	 *2011-2011-12-17-下午08:16:46 by 460932465
	 * @return JSon to dwz
	 * @param int $state
	 * @param string $message
	 */
	protected function _dwzjson($state,$message)
	{
		$navTabId=isset($this->_context->navTabId)?$this->_context->navTabId:null;
		$callbackType=isset($this->_context->callbackType)?$this->_context->callbackType:null;
		$forwardUrl=isset($this->_context->forwardUrl)?$this->_context->forwardUrl:NULL;
		$result=array(
			'statusCode'=>$state,
			'message'=>$message,
			'navTabId'=>$navTabId,
			'callbackType'=>$callbackType,
			'forwardUrl'=>$forwardUrl
		);
			exit(json_encode($result));
	}	
/**
     * 
     *2011-12-20-下午04:25:56 by 460932465
     * @access 获取查询参数数组 ...
     */
	protected function get_param()
	{
		$this->param=$this->_context->post();
		unset($this->param['ns']);
		unset($this->param['controller']);
		unset($this->param['action']);
		unset($this->param['module']);
		
		if(isset($this->param['numPerPage']))
		{
			unset($this->param['numPerPage']);
		}
		if(isset($this->param['pageNum']))
		{
			unset($this->param['pageNum']);
		}
		if(isset($this->param['numPerPage']))
		{
			unset($this->param['numPerPage']);
		}
		if(isset($this->param['undefined']))
		{
			unset($this->param['undefined']);
		}
		if(isset($this->param['orderField']))
		{
			unset($this->param['orderField']);
		}
		if(isset($this->param['orderDirection']))
		{
			unset($this->param['orderDirection']);
		}
		
		if (isset($this->param['_']))unset($this->param['_']);
		
		//设置搜索POST的地址
		$this->_view['param']=$this->param;
	}
	//-------------------------------------------------------end by
    /**
     * 控制器动作要渲染的数据
     *
     * @var array
     */
    protected $_view = array();

    /**
     * 控制器要使用的视图类
     *
     * @var string
     */
    protected $_view_class = 'QView_Render_PHP';

    /**
     * 控制器要使用的视图
     *
     * @var string
     */
    protected $_viewname = null;

    /**
     * 控制器所属的应用程序
     *
     * @var CommunityApp
     */
    protected $_app;

    /**
     * 构造函数
     */
    function __construct($app)
    {
        parent::__construct();
        $this->_app = $app;
    }

    /**
     * 执行指定的动作
     *
     * @return mixed
     */
    function execute($action_name, array $args = array())
    {
        $action_method = "action{$action_name}";

        // 执行指定的动作方法
        $this->_before_execute();

        #IFDEF DBEUG
        QLog::log('EXECUTE ACTION: '. get_class($this) . '::' . $action_method . '()', QLog::DEBUG);
        #ENDIF
        $response = call_user_func_array(array($this, $action_method), $args);
        $this->_after_execute($response);
        if (is_null($response) && is_array($this->_view))
        {
            // 如果动作没有返回值，并且 $this->view 不为 null，
            // 则假定动作要通过 $this->view 输出数据
            $config = array('view_dir' => $this->_getViewDir());
            $response = new $this->_view_class($config);
            $response->setViewname($this->_getViewName())->assign($this->_view);
            $this->_before_render($response);
        }
        elseif ($response instanceof $this->_view_class)
        {
            $response->assign($this->_view);
            $this->_before_render($response);
        }

        return $response;
    }

    /**
     * 指定的控制器动作未定义时调用
     *
     * @param string $action_name
     */
    function _on_action_not_defined($action_name)
    {
    }

    /**
     * 执行控制器动作之前调用
     */
    protected function _before_execute()
    {
    	
    	//dump($_SESSION['power']);die;
    	//验证登陆
    	if (in_array($this->_context->controller_name, array('login','interface','astgo','wap','asp','default','call','api')) )
    	{
    	
    	}else 
    	{
	    	if (!isset($_SESSION['acct']) )
	    	{
	    		echo $this->_redirectMessage('错误', '您没有登陆', url('admin::login'))->execute();
	    		exit();
	    	}else if (!isset($_SESSION['power']))
	    	{
	    		echo $this->_redirectMessage('错误', '您没有任何权限', url('admin::login'))->execute();
	    		exit();
	    	}else if (!isset($_SESSION['power'][strtolower($this->_context->controller_name)]) || !in_array(strtolower($this->_context->action_name),$_SESSION['power'][strtolower($this->_context->controller_name)]))
	    	{
	    		echo $this->_redirectMessage('错误', '当前页面您没有权限访问', url('admin::login'))->execute();
	    		exit();
	    	}
    	}
    	
    }

    /**
     * 执行控制器动作之后调用
     *
     * @param mixed $response
     */
    protected function _after_execute(& $response)
    {
    }

    /**
     * 渲染之前调用
     *
     * @param QView_Render_PHP
     */
    protected function _before_render($response)
    {
    }

    /**
     * 准备视图目录
     *
     * @return array
     */
    protected function _getViewDir()
    {
        if ($this->_context->module_name)
        {
            $dir = Q::ini('app_config/MODULE_DIR') . "/{$this->_context->module_name}/view";
        }
        else
        {
            $dir = Q::ini('app_config/APP_DIR') . '/view';
        }

        if ($this->_context->ns)
        {
            $dir .= "/{$this->_context->ns}";
        }
        return $dir;
    }

    /**
     * 确定要使用的视图
     *
     * @return string
     */
    protected function _getViewName()
    {
        if ($this->_viewname === false)
        {
            return false;
        }
        $viewname = empty($this->_viewname) ? $this->_context->action_name : $this->_viewname;
        return strtolower("{$this->_context->controller_name}/{$viewname}");
    }

    /**
     * 显示一个提示页面，然后重定向浏览器到新地址
     *
     * @param string $caption
     * @param string $message
     * @param string $url
     * @param int $delay
     * @param string $script
     *
     * @return QView_Render_PHP
     */
    protected function _redirectMessage($caption, $message, $url, $delay = 3, $script = '')
    {
        $config = array('view_dir' => $this->_getViewDir());
        $response = new $this->_view_class($config);
        $response->setViewname('redirect_message');
        $response->assign(array(
            'message_caption'   => $caption,
            'message_body'      => $message,
            'redirect_url'      => $url,
            'redirect_delay'    => $delay,
            'hidden_script'     => $script,
        ));
        return $response;
    }
	
	function _check_admin()
	{
		return isset($_SESSION['ADMIN_USER']) && $_SESSION['ADMIN_USER'];
	}
	function _check_Admin_Login()
	{
		if (!isset($_SESSION['acct']))
		{
			header(url('login'));
			exit();
		}
	}
	function _format_appendSql()
	{
		$append = array();
		if (isset($_SESSION['acct']))
		{
			if ($_SESSION['acct']['admin_id'] == -1 && $_SESSION['acct']['agent_id'] == -1)
			{
			//为管理
				//$append['']
			}else
			{
				$append['agent_id'] = $_SESSION['acct']['id'];
			}
		}
		return $append;
		//dump($_SESSION['acct']);
	}
}

